﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMove : MonoBehaviour
{
    public bool isLoop = false;
    public Transform wayPointList;
    public float wayPointTriggerRange = 2f;
    public List<Transform> wayPoints = new List<Transform>();
    public float moveSpeed=10f;
    public float roatatorEfficiency = 0.5f;
    public int wp_index = 0;
    // Start is called before the first frame update
    void Start()
    {
        if (wayPointList != null)
        {
            initWayPoints(wayPointList);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (wayPointList != null)
        {
            //确定目标方向
            Vector3 direction = wayPoints[wp_index].position - transform.position;

            if (Vector3.Distance(wayPoints[wp_index].position, transform.position) < wayPointTriggerRange)
            {
                //切换到下一个路径点
                if (!isLoop)    //不循环
                {
                    if (wp_index < wayPoints.Count - 1)
                        wp_index++;
                }else
                {
                    wp_index = ++wp_index % wayPoints.Count;
                    //print(wp_index);
                }
            }
            //transform.LookAt(direction);  //瞬间完成
            //球形插值旋转
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime* roatatorEfficiency/*旋转快慢，越大越快*/);
            transform.Translate(moveSpeed* Vector3.forward * Time.deltaTime);
        }
    }

    public bool initWayPoints(Transform wayPointList)
    {
        if(wayPointList==null)
        {
            return false;
        }
        int i = 0;
        while(wayPointList.Find("WayPoint ("+i+")")!=null)
        {
            wayPoints.Insert(i, wayPointList.Find("WayPoint (" + i + ")"));
            i++;
        }
        return true;
    }

}
